<script>
//节点类
class Node{
    constructor(data){
        this.data = data
        this.next = null
    }
}
//链表类
class SinglyLinkedList{
    constructor(){
        this.head = new Node() //head指向头节点
    }
    //在链表组后添加节点
    add(data){
        let node = new Node(data)
        let current = this.head
        while(current.next){
            current = current.next
        }
        current.next = node
    }
    //添加到指定位置（添加到current节点的后面）
    addAt(index, data){
        let node = new Node(data)
        let current = this.head
        let counter = 1
        while(current){
            if(counter === index){
                node.next = current.next
                current.next = node
            }
            current = current.next
            counter++
        }
    }
    //删除某个位置的节点（删除current节点后面的一个节点）
    removeAt(index){
        let current = this.head
        let counter = 1
        while(current.next){
            if(counter === index){
                current.next = current.next.next
            }
            current = current.next
            counter++
        }
    }
    //反转链表（修改当前current节点的next）
    reverse(){
        let current = this.head.next
        let prev = this.head
        while(current){
            let next = current.next
            //反转：改变当前节点指针。若当前节点是第一个（即头节点后面的）节点，则此节点的next为null，否则next指向他的上一个节点
            current.next = prev===this.head ? null : prev
            prev = current
            current = next
        }
        this.head.next = prev
    }
}


</script>